<?php 

namespace IMT\ServicesBundle\Controller;

use JMS\Serializer\SerializationContext;

use IMT\CommentBundle\Entity\Comment;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\Rest\Util\Codes;

class CommentRestController extends Controller
{
	/**
	 * GET /comment/{eventId}
	 *
	 * @param string $eventId
	 * @return Response
	 */
	public function getCommentAction($commentId)
	{			
		if(intval($commentId) == 0)
	    	throw new \InvalidArgumentException(400, 'L\'id est incorrect : '.$commentId);
	    
    	// Récupération de l'comment
    	$repository = $this->getDoctrine()->getRepository('IMTCommentBundle:Comment');
   		$comment = $repository->findOneById($commentId);
   		
   		if (!$comment)
   			throw new NotFoundHttpException('Le commentaire ayant l\'id '.$commentId.' n\'existe pas');
   		
   		
   		// Vérification des droits d'acces
   		$securityContext = $this->get('security.context');   		
   		
   		$context = new SerializationContext();
   		$context->setVersion('1.0');
   		$context->setGroups(array('comment_details', 'user_list'));
   			   		
		$view = View::create()
			->setStatusCode(200)
			->setData($comment)
			->setSerializationContext($context);

		return $this->get('fos_rest.view_handler')->handle($view);
	}
	
	/**
	 * Creates a new Thread from the submitted data.
	 *
	 * @param Request $request The current request
	 *
	 * @return View
	 */
	public function postCommentAction(Request $request)
	{
		$idComment = 0;
	
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		if('POST' == $request->getMethod()){
			$idComment = $request->request->get('comment_id');
			$typeEvent = $request->request->get('event_type');
			$idEvent = $request->request->get('event_id');
			
			$validator = $this->get('validator');
			
			$comment = null;
									
			$idThread = 'type['.$typeEvent.']_channel[event_'.$idEvent.']';
			$thread = $this->container->get('fos_comment.manager.thread')->findThreadById($idThread);
			
			if (null === $thread) {
				$thread = $this->container->get('fos_comment.manager.thread')->createThread();
				$thread->setId($idThread);
				$thread->setPermalink($request->getUri());
					
				// Add the thread
				$this->container->get('fos_comment.manager.thread')->saveThread($thread);
			}
			
			$commentManager = $this->container->get('fos_comment.manager.comment');
	
			if($idComment == 0){
				$comment = $commentManager->createComment($thread);
				
				$comment->setBody($request->request->get('comment_body'));
				
				$commentManager->saveComment($comment);
			} else {
				$comment = $em->getRepository('IMTCommentBundle:Comment')->find($idComment);
					
				if(!$comment)
					throw $this->createNotFoundException('Le commentaire "'.$idComment.'" n\'existe pas');
				
				$comment->setBody($request->request->get('comment_body'));
			}
									
			//return $viewHandler->handle($this->createErrorViewResponse($comment));
			$errors = $validator->validate($comment);
			
			if(count($errors) > 0){
				$return['errors'] = $errors;
			
				return $viewHandler->handle($this->createErrorViewResponse($return));
			} else {
				$em = $this->getDoctrine()->getEntityManager();
				$em->persist($comment);
				$em->flush();
					
				$return['idComment'] = $comment->getId();
			
				return $viewHandler->handle($this->createSuccessViewResponse($return));
			}
		} else {
			throw new MethodNotAllowedException('POST');
		}
	
	}
	
	public function deleteCommentAction($id)
	{
		$em = $this->getDoctrine()->getEntityManager();
		$viewHandler = $this->get('fos_rest.view_handler');
			
		$entity = $em->getRepository('IMTCommentBundle:Comment')->find($id);
		
		$user = $this->get('security.context')->getToken()->getUser();
		
		if (!$entity) {
			throw $this->createNotFoundException('Le commentaire "'.$id.'" n\'existe pas');
		} 
		
		$em->remove($entity);
		$em->flush();
		
		return $viewHandler->handle($this->createSuccessViewResponse(array('idComment' => $id)));
	}
	
	private function createSuccessViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(200)
		->setData($return);
	
		return $view;
	}
	
	private function createErrorViewResponse($return)
	{
		$view = View::create()
		->setStatusCode(Codes::HTTP_BAD_REQUEST)
		->setData($return);
	
		return $view;
	}
}